<template>
   <div class="wrapper">
	 <el-container>
	   <el-header>
		 <h1>走访记录</h1>
	   </el-header>
	   
	   <el-main>
		 <el-scrollbar max-height="78vh">
			<!-- 家庭信息 -->
		<el-card style="width: 820px;">
		  <h3>家庭信息</h3>
		  <el-form ref="familyForm" :model="family" :rules="familyRules" label-width="120px">
			<div class="form-row">
			  <el-form-item class="form-item" label="户号"  style="width: 400px;" prop="fId">
				<el-input v-model="family.fId" maxlength="10" placeholder="请输入贫困户编号"></el-input>
			  </el-form-item>
			</div>
			<div class="form-row">
			  <el-form-item class="form-item" label="户主姓名" prop="pName">
				<el-input v-model="family.pName" placeholder="请输入户主姓名"></el-input>
			  </el-form-item>
			  <el-form-item class="form-item" label="户主身份证" prop="pNumber">
				<el-input v-model="family.pNumber" placeholder="请输入户主身份证号" maxlength="18"></el-input>
			  </el-form-item>
			</div>
			<div class="form-row">
			  <el-form-item class="form-item" label="省" prop="province">
				<el-select v-model="family.province" @change="onProvinceChange">
				  <el-option v-for="province in provinces" :key="province.code" :label="province.name" :value="province.name"></el-option>
				</el-select>
			  </el-form-item>
			  <el-form-item class="form-item" label="市" prop="city">
				<el-select v-model="family.city" @change="onCityChange">
				  <el-option v-for="city in cities" :key="city.code" :label="city.name" :value="city.name"></el-option>
				</el-select>
			  </el-form-item>
			</div>
			<div class="form-row">
			  <el-form-item class="form-item" label="县(区)" prop="county">
				<el-select v-model="family.county" @change="onCountyChange">
				  <el-option v-for="county in counties" :key="county.code" :label="county.name" :value="county.name"></el-option>
				</el-select>
			  </el-form-item>
			  <el-form-item class="form-item" label="乡(镇)" prop="township">
				<el-select v-model="family.township" @change="onTownshipChange">
				  <el-option v-for="township in townships" :key="township.code" :label="township.name" :value="township.name"></el-option>
				</el-select>
			  </el-form-item>
			</div>
			<el-form-item label="村" prop="village">
			  <el-input v-model="family.village" placeholder="请输入村名称"></el-input>
			</el-form-item>
		  </el-form>
		</el-card>
		
		 <!-- 贫困人员信息 -->
			<el-card v-for="(poor, index) in poorPeople" :key="index" class="poor-person-card" shadow="hover">
				<h3>家庭成员 {{ index + 1 }}</h3>
				<el-form ref="fm" :model="poor" :rules="poorRules" label-width="120px" >
				  <div class="form-row">
					<el-form-item class="form-item" label="姓名" prop="name">
					  <el-input v-model="poor.name" maxlength="15" ></el-input>
					</el-form-item>
					<el-form-item class="form-item" label="身份证号" prop="idNumber">
					  <el-input v-model="poor.idNumber" maxlength="18"></el-input>
					</el-form-item>
				  </div>
				  <div class="form-row">
					<el-form-item class="form-item" label="民族" prop="nation">
					  <el-input v-model="poor.nation" maxlength="15"></el-input>
					</el-form-item>
					<el-form-item class="form-item" label="性别" prop="sex">
					  <el-select v-model="poor.sex">
						<el-option label="女" :value="0"></el-option>
						<el-option label="男" :value="1"></el-option>
					  </el-select>
					</el-form-item>
				  </div>
				  <div class="form-row">
					<el-form-item class="form-item" label="是否是户主" prop="isHead">
					  <el-radio-group v-model="poor.isHead">
						<el-radio :label="true">是</el-radio>
						<el-radio :label="false">否</el-radio>
					  </el-radio-group>
					</el-form-item>
					<el-form-item class="form-item" label="与户主关系" prop="relation">
					  <el-input v-model="poor.relation" maxlength="50"></el-input>
					</el-form-item>
				  </div>
				  <div class="form-row">
					<el-form-item class="form-item" label="是否享有医保" prop="insurance">
					  <el-radio-group v-model="poor.insurance">
						<el-radio :label="true">是</el-radio>
						<el-radio :label="false">否</el-radio>
					  </el-radio-group>
					</el-form-item>
					<el-form-item class="form-item" label="是否享有低保" prop="basic">
					  <el-radio-group v-model="poor.basic">
						<el-radio :label="true">是</el-radio>
						<el-radio :label="false">否</el-radio>
					  </el-radio-group>
					</el-form-item>
				  </div>
				  <div class="form-row">
					<el-form-item class="form-item" label="工作情况" prop="work">
					  <el-input v-model="poor.work" type="textarea" :rows="4" maxlength="250"></el-input>
					</el-form-item>
					<el-form-item class="form-item" label="健康情况" prop="health">
					  <el-input v-model="poor.health" type="textarea" :rows="4" maxlength="250"></el-input>
					</el-form-item>
				  </div>
				</el-form>
				<el-button v-if="index !== 0" type="danger" @click="removePoorPerson(index)">移除此人员</el-button>
			</el-card>
		   
		   <div class="add">
				<el-button  type="primary" plain @click="addPoorPerson">添加家庭成员</el-button>
		   </div> 
		   
		   <!-- 走访信息 -->
			 <el-card style="margin-top: 20px;">
				 <h3>走访信息</h3>
				 <el-form ref="interviewForm" :model="interview" label-width="120px" :rules="interviewRules">
				   <!-- 走访日期 -->
				   <el-form-item label="走访时间" prop="time">
					 <el-date-picker 
					 v-model="interview.time" 
					 type="date" 
					 placeholder="请选择日期"
					 value-format="YYYY-MM-DD"></el-date-picker>
				   </el-form-item>
				   
				   <!-- 风险类型 -->
				   <el-form-item label="风险类型" prop="riskType">
					 <el-checkbox-group v-model="interview.riskType">
					   <el-checkbox label="1">人力风险</el-checkbox>
					   <el-checkbox label="2">物质风险</el-checkbox>
					   <el-checkbox label="3">自然风险</el-checkbox>
					   <el-checkbox label="4">金融风险</el-checkbox>
					   <el-checkbox label="5">社会风险</el-checkbox>
					 </el-checkbox-group>
				   </el-form-item>
				   
				   <!-- 风险备注 & 走访详情 -->
				   <div class="form-row">
					 <el-form-item class="form-item" label="风险备注">
					   <el-input v-model="interview.riskRemark" type="textarea" :rows="5" maxlength="250" placeholder="请输入风险备注"></el-input>
					 </el-form-item>
					 <el-form-item class="form-item" label="走访详情">
					   <el-input v-model="interview.detail" type="textarea" :rows="5" maxlength="250" placeholder="请输入交谈详情"></el-input>
					 </el-form-item>
				   </div>
				   
				   <!-- 年收入 & 负债 -->
				   <div class="form-row">
					 <el-form-item class="form-item" label="年收入" prop="income">
						 <el-input-number style="width: 260px;" v-model="interview.income"  :precision="2" :step="0.1" :max="1000000" :min="0" 
						 placeholder="请输入年收入金额(单位:元)"/>
					 </el-form-item>
					 <el-form-item class="form-item" label="负债" prop="liability">
						 <el-input-number style="width: 260px;" v-model="interview.liability"  :precision="2" :step="0.1" :max="1000000" :min="0"
						 placeholder="请输入负债金额(单位:元)"/>
					 </el-form-item>
				   </div>
				   
				   <div class="form-row">
					   <!-- 走访实况 -->
					   <el-form-item label="走访实况" prop="photo" class="form-item">
								<div style="width: 150px; height: 150px; overflow: hidden;">
								   <el-upload
								   list-type="picture-card"
								   :auto-upload="false"
								   action="#"
								   :limit="1"
								   :on-change="uploadFile"
								   :on-remove="removeFile">
									<el-icon><PictureFilled /></el-icon>
								   </el-upload>
								</div>
					   </el-form-item>
					   
					   <el-form-item  label="建议与意见" class="form-item">
					     <el-input v-model="interview.suggestion" type="textarea" :rows="5" maxlength="250" placeholder="请输入建议与意见"></el-input>
					   </el-form-item>
					</div>
				 </el-form>
			 </el-card>
	   
			<div class="save">
				 <el-button style="margin-top: 10px;" type="success" @click="submitForm" :icon="Save">提交</el-button>
			</div>

		 </el-scrollbar>
	   </el-main>
	 </el-container>
   </div>
</template>
  
<script setup>
import { ref ,onMounted ,watch ,reactive, nextTick, getCurrentInstance } from 'vue'
import Save from '@/components/icons/save' 
import { ElMessage } from 'element-plus'
import areaData from '@/area/pcas-code.json'
import { PictureFilled } from '@element-plus/icons-vue'
import { post, get , submitMultipleForms} from '@/axios'
import { userIdStore } from '@/stores'

const idStore = userIdStore()
const familyForm = ref(null) 
const interviewForm = ref(null)

const family = ref({
  fId: null,
  pName: '',
  pNumber: '',
  rId: null,
  province: '',
  city: '',
  county: '',
  township: '',
  village: '',
  vcId: idStore.userId
})

const poorPeople = ref([
  {
	pId: null,
    idNumber: '',
    name: '',
	nation: '',
	sex: null,
	isHead: true,
	relation: '户主本人',
	work: '',
	health: '',
	insurance: null,
	basic: null,
	fId: family.value.fId
  }
])

const interview = ref({
  id: null,
  vcId: idStore.userId,
  fId: family.value.fId,
  time: '',
  riskType: [],
  riskRemark: '',
  income: null,
  liability: null,
  suggestion: '',
  detail: '',
  photo: ''
})

function checkFamily (rule, value, callback) {
	get("/family/check",{ id:null, value, field: 'f_id' }, content => {
		if (content) {
			callback()
		} else {
			callback(new Error())
		}
	})
}

function checkPoor (rule, value, callback) {
	get("/poor/check",{ id:null, value, field: 'id_number'}, content => {
		if (content) {
			callback()
		} else {
			callback(new Error())
		}
	})
}

const familyRules = reactive({
	fId: [
		{ required: true, message: '请输入合法户号', trigger: 'blur' },
		{ validator: checkFamily, message: '该贫困户已经录入', trigger: 'blur' },
		{ pattern: /^\d{10}$/, message: '请输入合理的贫困户编号',trigger: 'blur' }
	],
	pName: [
		{ required: true, message: '请输入户主姓名', trigger: 'blur' },
	],
	pNumber: [
		{ required: true, message: '请输入户主身份证', trigger: 'blur' },
		{ pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的中国身份证号', trigger: 'blur' },
		{ validator: checkPoor, message: '该身份证号已经存在', trigger: 'blur' }
	],
	county: [
		{ required: true, message: '请选择所在县(区)', trigger: 'blur' }
	],
	city: [
		{ required: true, message: '请选择所在城市', trigger: 'blur' }
	],
	province: [
		{ required: true, message: '请选择所在省份', trigger: 'blur' }
	],
	township: [
		{ required: true, message: '请选择所在乡(镇)', trigger: 'blur' }
	],
	village: [
		{ required: true, message: '请输入所在村庄', trigger: 'blur' }
	]
})

const poorRules = reactive({
	name: [
		{ required: true, message: '请输入姓名', trigger: 'blur' },
	],
	idNumber: [
		{ required: true, message: '请输入身份证号', trigger: 'blur' },
		{ pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的中国身份证号', trigger: 'blur' },
		{ validator: checkPoor, message: '该身份证号已经存在', trigger: 'blur' }
	],
	nation: [
		{ required: true, message: '请输入民族', trigger: 'blur' },
	],
	sex: [
		{ required: true, message: '请选择性别', trigger: 'blur' },
	],
	isHead: [
		{ required: true, message: '请选择是否是户主', trigger: 'blur' },
	],
	relation: [
		{ required: true, message: '请输入与户主关系', trigger: 'blur' },
	],
	work: [
		{ required: true, message: '请输入工作情况', trigger: 'blur' },
	],
	health: [
		{ required: true, message: '请输入健康情况', trigger: 'blur' },
	],
	insurance: [
		{ required: true, message: '请选择是否有医保', trigger: 'blur' },
	],
	basic: [
		{ required: true, message: '请选择是否有低保', trigger: 'blur' },
	]
})

const interviewRules = reactive({
	time: [
		{ required: true, message: '请输入走访时间', trigger: 'blur' }
	],
	riskType: [
		{ required: true, message: '请选择风险类型', trigger: 'blur'}
	],
	income: [
		{ required: true, message: '请输入年收入', trigger: 'blur' }
	],
	liability: [
		{ required: true, message: '请输入负债金额', trigger: 'blur' }
	],
	photo: [
		{ required: true, message: '请上传走访实况', trigger: 'blue'}
	]

})

const provinces = ref([]);
const cities = ref([]);
const counties = ref([]);
const townships = ref([]);

onMounted(() => {
  provinces.value = areaData.map(province => ({
    name: province.name,
    code: province.code,
    cities: province.children || [],
  }));
});

// 选择省份后加载市
const onProvinceChange = (value) => {
  family.value.province = value;
  family.value.city = '';
  family.value.county = '';
  family.value.township = '';
  
  const selectedProvince = provinces.value.find(province => province.name === value);

  if (selectedProvince) {
    cities.value = selectedProvince.cities.map(city => ({
      name: city.name,
      code: city.code,
      counties: city.children || [],
    }));
  } else {
    cities.value = [];
  }

  counties.value = [];
  townships.value = [];
  family.value.rId = null;
};

// 选择市后加载县
const onCityChange = (value) => {
  family.value.city = value;
  family.value.county = '';
  family.value.township = '';

  const selectedCity = cities.value.find(city => city.name === value);

  if (selectedCity) {
    counties.value = selectedCity.counties.map(county => ({
      name: county.name,
      code: county.code,
      townships: county.children || [],
    }));
  } else {
    counties.value = [];
  }

  townships.value = [];
  family.value.rId = null;
};

// 选择县后加载乡
const onCountyChange = (value) => {
  family.value.county = value;
  family.value.township = '';

  const selectedCounty = counties.value.find(county => county.name === value);

  if (selectedCounty) {
    townships.value = selectedCounty.townships.map(township => ({
      name: township.name,
      code: township.code,
    }));
  } else {
    townships.value = [];
  }

  family.value.rId = null;
};

// 选择乡镇后绑定 rId
const onTownshipChange = (value) => {
  family.value.township = value;
  const townshipData = townships.value.find(township => township.name === value);
  family.value.rId = townshipData ? townshipData.code : null;
};
const fm = ref()
const addPoorPerson = () => {
	fm.value[poorPeople.value.length - 1].validate(valid => {
		if (valid) {
			poorPeople.value.push({
			  pId: null,
			  idNumber: '',
			  name: '',
				nation: '',
				sex: null,
				isHead: false,
				relation: '',
				work: '',
				health: '',
				insurance: null,
				basic: null,
				fId: family.value.fId
			})
		}
	})
}

// 监听 family.pName 和 family.pNumber 的变化
watch(
  () => [family.value.pName, family.value.pNumber],
  ([newName, newNumber]) => {
    // 更新 poorPeople 第一个对象中的 idNumber 和 name
    if (poorPeople.value.length > 0) {
      poorPeople.value[0].name = newName;
      poorPeople.value[0].idNumber = newNumber;
    }
  }
);

//同步更新访谈记录中fId
watch(
	() => family.value.fId,
	(newVal) => {
		if (newVal) {
			interview.value.fId = newVal
			poorPeople.value.forEach(poor => {
				poor.fId = newVal
			})
		}
	}
)

const removePoorPerson = (index) => {
  poorPeople.value.splice(index, 1)
}


function submitForm () {
	submitMultipleForms(
		"/upInterview/add", 
		{ 
			fId: family.value.fId, pName: family.value.pName, pNumber: family.value.pNumber, rId: family.value.rId, province: family.value.province, city: family.value.city, county: family.value.county, township: family.value.township, village: family.value.village ,
			poorPeople: JSON.stringify(poorPeople.value),
			vcId: interview.value.vcId,time: interview.value.time,riskType: interview.value.riskType,riskRemark: interview.value.riskRemark,income: interview.value.income,liability: interview.value.liability,suggestion: interview.value.suggestion,detail: interview.value.detail,photo: interview.value.photo
		},
		response => {
			if(response)window.location.reload()
		},
		[familyForm, interviewForm]
	);
}

// 默认上传文件
const fileList = reactive([])

function uploadFile ( file ) {
	console.dir(file)
	interview.value.photo = file.raw
}
function removeFile () {
	interview.value.photo = null
}
</script>

  
<style scoped lang="scss">
.el-container {
	display: flex;
	justify-content: center;
	align-items: center;
	border: 5px solid; /* 边框大小 */  
	box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.5); /* 阴影效果 */  
	border-radius: 10px;
	margin-bottom: 0px;
}
.el-header {
	line-height: 60px;
	letter-spacing: 1.2rem;
	h1 {
		font-size: 1.5rem;
	}
}

.form-row {
  display: flex;
  gap: 20px; 
  margin-top: 10px;
  .form-item {
    flex: 1; 
  }
}
.poor-person-card {
  margin-bottom: 20px;
}
.add,.save {
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>